package com.example.sw_zx_app.service;

import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

@org.springframework.stereotype.Service
public class OpenApiZongxinAppServiceImpl implements OpenApiZongxinAppService {
    @Value("${file.baseDir}")
    private String fileBaseDir;

    @Value("${file.FTPDir}")
    private String FTPDir;

    @Override
    public void appReceivePicSync2(String orderNO, MultipartFile[] multipartFiles, String isEnd, JsonNode jsonNode) {

        System.out.println("---开始接受zxApp传输图片---");
        Path path = Paths.get(fileBaseDir + "/MINIO/" + orderNO + "_IR无人机巡检任务_");
        if (!Files.exists(path)) {
            try {
                Files.createDirectories(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
//
        }
        try {
                for (MultipartFile multipartFile : multipartFiles) {
                    // 检查文件是否被锁定
//                    Path temp = Paths.get(path+"\\"+multipartFile.getOriginalFilename());
                    if (multipartFile.getOriginalFilename() == null) {
                        continue;
                    }
                    String fileName = multipartFile.getOriginalFilename();
                    Path temp = path.resolve(fileName);
                    if (Files.exists(temp) && Files.isWritable(temp)) {
                        System.out.println("文件已存在："+ multipartFile.getOriginalFilename());
                    }
                    //temp 为改文件目录+文件名
//                    Files.write(temp, multipartFile.getBytes());
                    InputStream inputStream = multipartFile.getInputStream();
                    Files.copy(inputStream, temp, StandardCopyOption.REPLACE_EXISTING);
                }

        } catch (IOException e) {
            e.printStackTrace();
        }
        //图片还没上传结束
        if (isEnd != "1") {
            return;
        }

//        移动到ftp目录自动同步到3区服务
        Path targetPath = Paths.get(FTPDir + orderNO);
        if (!Files.exists(targetPath)) {
            try {
                Files.createDirectories(targetPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {

            long fileCount = Files.walk(path)
                    .filter(Files::isRegularFile)
                    .count();

            for (Path file : stream) {
                Path targetFile = targetPath.resolve(file.getFileName());
                Files.move(file, targetFile, StandardCopyOption.REPLACE_EXISTING);
            }

            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
            String temp = timestamp+"_"+fileCount+".txt";
            String filePath = targetPath +"/"+ temp;
            // 要写入文件的内容
            String content = jsonNode.asText();

            // 创建 File 对象
            File file = new File(filePath);

            // 创建文件并写入内容
            FileWriter writer = new FileWriter(file);
            writer.write(content);

            System.out.println("文件创建并写入成功！:"+temp);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private String copeFileName(String fileName) {
        String originalFilename = fileName;

        // 找到最后两个 _ 的位置
        int lastUnderscoreIndex = originalFilename.lastIndexOf('_');
        int secondLastUnderscoreIndex = originalFilename.lastIndexOf('_', lastUnderscoreIndex - 1);

        // 截取最后第二个 _ 和最后一个 _ 之间的数据
        String partToReplace = originalFilename.substring(secondLastUnderscoreIndex + 1, lastUnderscoreIndex);

        // 构造新的文件名
        String newFilename = originalFilename.substring(0, secondLastUnderscoreIndex + 1) +
                originalFilename.substring(lastUnderscoreIndex + 1, originalFilename.length() - 4) +
                "_" + partToReplace + ".jpg";

        System.out.println("新的文件名是: " + newFilename);
        return newFilename;
    }

    // 每周一凌晨0点执行任务
    @Scheduled(cron = "0 0 1 1 * ?")
    public void deleteFilesInDirectory() {
        String dirPath = FTPDir;
        System.out.println("执行定时任务: 删除指定目录下的文件, 时间: " + LocalDateTime.now());

        try {
            Path dir = Paths.get(dirPath);
            if (Files.exists(dir) && Files.isDirectory(dir)) {
                Files.list(dir).forEach(path -> {
                    try {
                        Files.delete(path); // 删除文件
                        System.out.println("已删除文件: " + path);
                    } catch (Exception e) {
                        System.err.println("删除文件失败: " + path);
                        e.printStackTrace();
                    }
                });
            } else {
                System.err.println("指定的目录不存在或不是一个目录: " + dirPath);
            }
        } catch (Exception e) {
            System.err.println("遍历目录失败: " + dirPath);
            e.printStackTrace();
        }
    }


}
